package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 类描述
 *
 * @author: Fred
 * @email 453086@qq.com
 * @create: 2024-10-19 16:50
 */
@Configuration
public class ThreadConfiguration {

    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

    @Bean
    public ThreadPoolTaskExecutor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int availableProcessors = Runtime.getRuntime().availableProcessors();

        // 配置核心线程数
        executor.setCorePoolSize(availableProcessors);
        // 配置最大线程数
        executor.setMaxPoolSize(availableProcessors*2);
        // 配置队列大小
        executor.setQueueCapacity(1000);
        // 线程的名称前缀
        executor.setThreadNamePrefix("Executor-");
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 执行初始化
        executor.initialize();

        return executor;
    }
}
